import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/utils/custom_event_bus.dart';
import 'package:enterprise_v6_app/app/core/utils/file_util.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/values/gaps.dart';
import 'package:enterprise_v6_app/app/core/values/images.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/list_by_book_id_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/course_center/integrated_theme/course_detail_detail_page/course_detail/course_detail_detail_page/train_directory_detail/train_directory_detail_controller.dart';
import 'package:enterprise_v6_app/app/modules/application/education/course_center/integrated_theme/course_detail_detail_page/course_detail_detail_page_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';

///人脸识别后的课程详情 目录
class TrainDirectoryDetailPage extends StatelessWidget {
  TrainDirectoryDetailPage({super.key});

  final controller = Get.put(TrainDirectoryDetailController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (_) {
          return SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 10.w, horizontal: 16.w),
              color: Colors.white,
              child: Column(
                children: [
                  _topWidget(),
                  _bottomWidget(),
                  AppGaps.vGap10,
                ],
              ),
            ),
          );
        });
  }

  ///除数是0 返回NaN在Dart编程语言中，"NaN" 代表 "Not a Number"，它是一种特殊的数值，
  ///表示一个无效或未定义的数值。通常情况下，NaN用于表示数学运算中的非法操作，
  ///比如0除以0，或者对负数开平方等。当这些操作无法产生有效的数值结果时，就会得到NaN。
  int _percentage(ListByBookIdEntity e) {
    final int deadline = e.deadline ?? 0;
    final int totalDuration = e.totalDuration ?? 0;
    final double percentage = deadline / totalDuration;
    return ((percentage.isNaN ? 0 : percentage) * 100).toInt();
  }

  Widget _topWidget() {
    return Column(
      children: controller.listByBookIdEntity!
          .map((e) => Container(
                padding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 10.w),
                decoration: e.click
                    ? BoxDecoration(
                        color: const Color(0x1A5C6DFF),
                        borderRadius: BorderRadius.circular(4.r),
                      )
                    : const BoxDecoration(),
                child: e.resourceTypeDicId == '6ac697ee-378d-48e8-95ae-53146ab43544' //录播课
                    ? Row(
                        children: [
                          Text(
                            '${e.directoryName}',
                            style: TextStyle(
                              color: const Color(0xFF262F38),
                              fontWeight: FontWeight.w400,
                              fontSize: 14.sp,
                            ),
                          ),
                          const Spacer(),
                          Text(
                            e.click ? '正在播放' : '${'${_percentage(e)}'}%',
                            style: TextStyle(
                              color: const Color(0xFF5C6DFF),
                              fontWeight: FontWeight.w400,
                              fontSize: 14.sp,
                            ),
                          ),
                          AppGaps.hGap12,
                          SvgPicture.asset(AppImages.icon_train_directory_play),
                        ],
                      )
                    : Row(
                        children: [
                          Text(
                            '${e.directoryName}',
                            style: TextStyle(
                              color: const Color(0xFF262F38),
                              fontWeight: FontWeight.w400,
                              fontSize: 14.sp,
                            ),
                          ),
                          const Spacer(),
                          Text(
                            e.deadline == 1 && e.totalDuration == 1 ? '已看' : '未看',
                            style: TextStyle(
                              color: const Color(0xFF5C6DFF),
                              fontWeight: FontWeight.w400,
                              fontSize: 14.sp,
                            ),
                          ),
                          AppGaps.hGap12,
                          SvgPicture.asset(AppImages.icon_train_courseware),
                        ],
                      ),
              ).clickOnce(() {
                if (controller.topListByBookIdEntity != null &&
                    controller.topListByBookIdEntity?.id == e.id &&
                    e.resourceTypeDicId == '6ac697ee-378d-48e8-95ae-53146ab43544') {
                  //点击相同的视频 不处理
                  return;
                }
                //清除所有的条目
                for (var v in controller.listByBookIdEntity!) {
                  v.click = false;
                }
                if (e.resourceTypeDicId == '6ac697ee-378d-48e8-95ae-53146ab43544') {
                  e.click = true;
                  //录播课 播放视频操作
                  // AppToast.show('录播课');
                  //发送事件 url播放 资源附件
                  CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPEDIRECTORYFILE, '${Interface.fileUrl}${e.directoryFile}'));
                  //发送目录的id
                  CustomEventBus.getInstance().fire(MyEntity(MyEntity.TYPEDIRECTORYFILEID, '${e.id}'));
                  //设置当前播放进度
                  CustomEventBus.getInstance().fire(MyEntity(MyEntity.DEADLINE, e.deadline ?? 0));
                  //当我每次点击的时候都要刷星视频进度并告诉过后端
                  //上一个视频的      不为null 和不是当前对象
                  if (controller.topListByBookIdEntity != null &&
                      controller.topListByBookIdEntity?.id != e.id &&
                      controller.topListByBookIdEntity?.resourceTypeDicId == '6ac697ee-378d-48e8-95ae-53146ab43544') {
                    //如果上一个是课件不操作-》只对视频录播发送
                    final Duration? totalDurationInSeconds = Get.find<CourseDetailDetailPageController>().videoKey.currentState?.totalDuration();
                    final Duration? currentPositionDurationInSeconds =
                        Get.find<CourseDetailDetailPageController>().videoKey.currentState?.currentPositionDuration();
                    //出入上一个topListByBookIdEntity 的目录id
                    controller.addCourseWatchRecord(
                        totalDurationInSeconds?.inSeconds, currentPositionDurationInSeconds?.inSeconds, controller.topListByBookIdEntity?.id, e.id);
                  }
                  //将当前对象赋值
                  controller.topListByBookIdEntity = e;
                } else {
                  //视频暂停
                  Get.find<CourseDetailDetailPageController>().videoKey.currentState?.pause();
                  if (e.deadline == 1 && e.totalDuration == 1) {
                    //已看就不操作
                  } else {
                    //未看
                    //课件是否已看 都传1 --》已看
                    controller.addCourseWatchRecordK(1, 1, controller.topListByBookIdEntity?.id);
                  }
                  //课件             资源附件
                  // AppToast.show('课件');
                  FileUtils.openFile(e.directoryFile ?? '', title: '文件名称');
                  if (controller.topListByBookIdEntity?.resourceTypeDicId == '6ac697ee-378d-48e8-95ae-53146ab43544') {
                    //上一个视频的      不为null 和不是当前对象
                    if (controller.topListByBookIdEntity != null && controller.topListByBookIdEntity?.id != e.id) {
                      final Duration? totalDurationInSeconds = Get.find<CourseDetailDetailPageController>().videoKey.currentState?.totalDuration();
                      final Duration? currentPositionDurationInSeconds =
                          Get.find<CourseDetailDetailPageController>().videoKey.currentState?.currentPositionDuration();
                      //出入上一个topListByBookIdEntity 的目录id
                      controller.addCourseWatchRecord(totalDurationInSeconds?.inSeconds, currentPositionDurationInSeconds?.inSeconds,
                          controller.topListByBookIdEntity?.id, controller.topListByBookIdEntity?.id);
                    }
                  }
                  //将当前对象赋值(上一个对象)永远是录播的
                  controller.topListByBookIdEntity = controller.topListByBookIdEntity;
                }
              }))
          .toList(),
    );
  }

  Widget _bottomWidget() {
    return Container(
      height: 38.w,
      decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: const Color(0xC28DB1FF).withOpacity(1), // 阴影颜色
              offset: const Offset(0, 1), // 阴影的偏移量，向上偏移，即上方阴影
              blurRadius: 0.5, // 阴影的模糊半径
              // spreadRadius: 1.0, // 阴影的扩散半径
            ),
          ],
          // border: Border.all(color: const Color(0xC28DB1FF).withOpacity(0.5), width: 1.w),
          borderRadius: BorderRadius.circular(4.r),
          gradient: const LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [
            Color(0xFFF3F7FF),
            Color(0xFFFFFFFF),
          ])),
      padding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 10.w),
      child: Row(
        children: [
          Text(
            '练习题',
            style: TextStyle(
              color: const Color(0xFF262F38),
              fontWeight: FontWeight.w500,
              fontSize: 14.sp,
            ),
          ),
          const Spacer(),
          Text(
            '开始',
            style: TextStyle(
              color: const Color(0xFF5C6DFF),
              fontWeight: FontWeight.w400,
              fontSize: 16.sp,
            ),
          ).clickOnce(controller.startDoingQuestions),
          AppGaps.hGap12,
          Text(
            '练习记录',
            style: TextStyle(
              color: const Color(0xFF5C6DFF),
              fontWeight: FontWeight.w400,
              fontSize: 16.sp,
            ),
          ).clickOnce(controller.practiceRecords),
        ],
      ),
    );
  }
}
